package mapEditor.utils;

//import debug.*;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JDialog;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import mapEditor.MapEditor;
import debug.Debug;

public class ValueType
{ private Vector<ChangeListener> CHANGE_LISTENERS=new Vector<ChangeListener>();

  public String getClassName()
  { String className=getClass().getName();
    int idx=className.lastIndexOf('.');
    if(idx>0) className=className.substring(idx+1);
	return(className);
  }

  public void add(ChangeListener changeListener) { CHANGE_LISTENERS.add(changeListener); }
  public void remove(ChangeListener changeListener) { CHANGE_LISTENERS.remove(changeListener); }
  
  protected void FIRE_CHANGE_EVENT(String msg)
  {
//	  Debug.TRACE("ValueType.FIRE_CHANGE_EVENT: "+getClassName()+" ATTRIBUTE("+msg+") CHANGED EVENT ?");
//    try { throw new Exception(""); } catch(Throwable e) { e.printStackTrace(); }
    ChangeEvent event=new ChangeEvent(this);
    for(Enumeration<ChangeListener> e=CHANGE_LISTENERS.elements();e.hasMoreElements();)
    { e.nextElement().stateChanged(event); }
  }

  //********************************************************************
  //*** INNER CLASS: EditValueTypeDialog
  //********************************************************************
  protected abstract class EditValueTypeDialog extends JDialog
  { static final long serialVersionUID=0; // AD'HOC
    private ValueType valueType;
    protected abstract void saveInitialValues();
    protected abstract void restoreInitialValues();
    
    ValueType extra1;
    protected void setExtraListener1On(ValueType extra1)
    { this.extra1=extra1; extra1.add(changeListener); }
    ValueType extra2;
    protected void setExtraListener2On(ValueType extra2)
    { this.extra2=extra2; extra2.add(changeListener); }
    
    private ChangeListener changeListener=new ChangeListener()
    { public void stateChanged(ChangeEvent e)
      { Debug.TRACE("ValueTypeDialog: SOME "+valueType.getClassName()+" ATTRIBUTES HAS CHANGED!");
        EditValueTypeDialog.this.repaint();
        MapEditor.repaint();
      }	
    };
    
    public EditValueTypeDialog(ValueType valueType,String title)
    { this.valueType=valueType;
      setTitle(title);
  	  saveInitialValues();
      addWindowListener(new WindowAdapter()
      { public void windowClosing(WindowEvent we) { cancel(); } });
      valueType.add(changeListener);
    }
    
    public void cancel()
    { restoreInitialValues();
      close();	
    }
    
    public void close()
    { valueType.remove(changeListener);
      if(extra1!=null) { extra1.remove(changeListener); extra1=null; }
      if(extra2!=null) { extra2.remove(changeListener); extra2=null; }
      dispose();	
    }

  }
}
